<template>
    <div :class="that.rootClass.value">
        <div class="inner-wrap">
            <d-player :src="that.playSrc.value" v-if="that.props.player === 'dplayer'" />
            <v-player :src="that.playSrc.value" :can-play="that.canPlay.value" :loop="that.props.loop" v-else-if="that.props.player === 'vplayer'" />
            <video controls :loop="that.props.loop" :src="that.playSrc.value" v-else />
        </div>
    </div>
</template>

<script lang="ts">
import '../common.css';
import './index.css';

import { IPropsExt } from '../type';
import DPlayer from './comp/dplayer.vue';
import VPlayer from './comp/vplayer.vue';
import { defineComponent, SetupContext, getCurrentInstance, ComponentInternalInstance, Ref, ref, watch } from 'vue';

class Init {
    props: IProps;
    context: SetupContext;
    current: ComponentInternalInstance;

    rootClass: Ref<string>;

    playSrc: Ref<string> = ref('');
    canPlay: Ref<boolean> = ref(false);

    constructor(props: IProps, context: SetupContext, current: ComponentInternalInstance) {
        this.props = props;
        this.context = context;
        this.current = current;

        this.rootClass = ref(`lv-player ${props.class || ''}`);

        this.updatePlaySrc(this.props.src);
        watch(
            () => this.props.src,
            async newVal => {
                this.updatePlaySrc(newVal);
            },
        );
    }

    /**
     * 更新播放地址，并检测是否可播放
     */
    async updatePlaySrc(src: string) {
        if (src) {
            this.playSrc.value = src;
            this.canPlay.value = true;
        } else {
            this.playSrc.value = '';
            this.canPlay.value = false;
        }
    }
}

interface IProps extends IPropsExt {
    src: string;
    loop: boolean;
    player: string;
}

export default defineComponent({
    name: 'lv-player',

    props: {
        class: { type: String, default: '' },

        loop: { type: Boolean, default: false },
        src: { type: String, default: '', required: true },
        player: {
            type: String,
            default: 'normal',
            validator(value: string) {
                return ['normal', 'dplayer', 'vplayer'].includes(value);
            },
        },
    },

    setup(props: IProps, context: SetupContext) {
        const current = getCurrentInstance() as ComponentInternalInstance;
        const that = new Init(props, context, current);
        return { that };
    },

    components: { DPlayer, VPlayer },
});
</script>
